'use strict';

const Service = require('egg').Service;
const Mock = require('mockjs');
const dayjs = require('dayjs');
dayjs().format()

class PageService extends Service {
    // 获取文章列表
    async getList() {
        const {
            ctx,
            app
        } = this;
        // // 模拟数据插入表中
        // const {list} = Mock.mock({
        //     "list|20":[
        //         {
        //             name:"@ctitle(4,8)",
        //             path:"@ctitle(4,20)",
        //             "order_num|0-3":1,
        //             "state|1":["草稿","已发布"],
        //             "read_num|1-100":1,
        //             publish_time:dayjs(Date.now()).format('YYYY-MM-DD')
        //         }
        //     ]            
        // });
        // // 循环list
        // list.forEach((item)=>{
        //     app.mysql.insert('pages',{...item});
        // });
        // return 'ok'
        const {
            pageSize,
            pageIndex,
            name,
            path,
            state,
        } = ctx.query;
        let sql = `select * from pages where 1=1 `;
        let countSql = `select count(id) as total from pages where 1=1 `
        if (name) {
            sql += `and name like "%${name}%" `
            countSql += `and name like "%${name}%" `
        }
        if (path) {
            sql += `and path like "%${path}%" `
            countSql += `and path like "%${path}%" `
        }
        if (state) {
            sql += `and state="${state}" `
            countSql += `and state="${state}" `
        }
        if (pageSize && pageIndex) {
            sql += `limit ${(pageIndex-1)*pageSize},${pageSize} `
        }
        const res = await app.mysql.query(sql);
        const [{
            total
        }] = await app.mysql.query(countSql);
        return {
            data: res,
            total,
        }
    }
    // 获取页面详情
    async getDetail() {
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.params;
        const res = await app.mysql.get('pages', {
            id
        })
        // 让访问量+1
        await app.mysql.update('pages', {
            id,
            read_num: ++res.read_num
        })
        return res
    }
    // 删除页面
    async delPage() {
        const {
            ctx,
            app
        } = this;
        const {
            id
        } = ctx.request.body;
        console.log(id);
        const res = await app.mysql.delete('pages', {
            id
        });
        return res
    }
    // 新建页面
    async addPage(){
        const {ctx,app} = this;
        const {
            name,
            path,
            order_num,
            state,
        } = ctx.request.body;
        const res = app.mysql.insert('pages',{
            name,
            path,
            order_num,
            read_num:0,
            state,
            publish_time:Date.now(),
        });
        return res
    }
}

module.exports = PageService;